package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.dto.QuestionExplainRequest;
import com.example.computer_exam_training_sys.dto.QuestionExplainResponse;
import com.example.computer_exam_training_sys.service.QuestionExplainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.SocketTimeoutException;

@RestController
@CrossOrigin
@RequestMapping("/api/question/explain")
public class QuestionExplainController {

    @Autowired
    private QuestionExplainService questionExplainService;

    @PostMapping
    public ResponseEntity<?> explainQuestion(@RequestBody QuestionExplainRequest request) {
        try {
            String result = questionExplainService.explainQuestion(
                request.getQuestionContent(), 
                request.getAnswer(), 
                request.getAnalysis()
            );
            return ResponseEntity.ok(new QuestionExplainResponse(result));
        } catch (SocketTimeoutException e) {
            return ResponseEntity
                .status(HttpStatus.REQUEST_TIMEOUT)
                .body(new QuestionExplainResponse("AI服务响应超时，请稍后重试"));
        } catch (Exception e) {
            return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new QuestionExplainResponse("AI服务暂时不可用，请稍后重试"));
        }
    }
}
